package com.wctj.api.business.common.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.incrementer.IKeyGenerator;
import com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.wctj.api.base.handler.LocalDateTimeFieldHandler;
import com.wctj.api.base.utils.JsonUtils;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.annotation.PostConstruct;

@Configuration
@EnableTransactionManagement
@MapperScan("com.wctj.api.**.dao")
public class MybatisPlusConfig implements ConfigurationCustomizer {

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
//        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());

        return interceptor;
    }

    @Override
    public void customize(MybatisConfiguration configuration) {
        TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
        typeHandlerRegistry.register(LocalDateTimeFieldHandler.class);
    }

    @PostConstruct
    public void init() {
        JacksonTypeHandler.setObjectMapper(JsonUtils.getMapper());
    }

    @Bean
    public SequenceKeyGenerator sequenceKeyGenerator() {
        return new SequenceKeyGenerator();
    }

    public static class SequenceKeyGenerator implements IKeyGenerator {

        @Override
        public String executeSql(String incrementerName) {
            return "SELECT NEXTVAL('" + incrementerName + "')";
        }

        @Override
        public DbType dbType() {
            return DbType.MYSQL;
        }
    }

}